package com.newdjk.newdoctor;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.util.Log;
import android.webkit.WebView;

import androidx.annotation.RequiresApi;

import com.bilibili.boxing.BoxingCrop;
import com.bilibili.boxing.BoxingMediaLoader;
import com.bilibili.boxing.loader.IBoxingMediaLoader;
import com.facebook.stetho.Stetho;
import com.liulishuo.filedownloader.FileDownloader;
import com.maning.librarycrashmonitor.MCrashMonitor;
import com.maning.librarycrashmonitor.listener.MCrashCallBack;
import com.newdjk.newdoctor.constants.AppConfig;
import com.newdjk.newdoctor.constants.EnvironmentManager;
import com.newdjk.newdoctor.db.gen.DaoMaster;
import com.newdjk.newdoctor.db.gen.DaoSession;
import com.newdjk.newdoctor.entity.GotoMainactivity;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.BadgeUtil;
import com.newdjk.newdoctor.utils.BoxingGlideLoader;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.viewHolder.MyLifecycleHandler;
import com.newdjk.newdoctor.wxapi.WXPayEntryActivity;
import com.newdjk.okhttp.RetrofitFactory;
import com.newdjk.okhttp.entity.DoctorInfoEntity;
import com.newdjk.okhttp.entity.Login;
import com.newdjk.okhttp.entity.MedicationCompanyEntity;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class MyApplication extends Application {
    public static DoctorInfoEntity DoctorInfoEntity;
    public static MedicationCompanyEntity medicationCompanyEntity;
    private static Context context;
    public static Login LoginEntity;
    public static boolean isLogin = false;
    public static IWXAPI mWxApi;
    public final static List<Activity> mActivities = new LinkedList<Activity>();
    public static DaoMaster daoMaster;
    public static DaoSession daoSession;
    public static int badgeNumber = 0;//红点显示
    public static String baiduToken = "";

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        FileDownloader.setup(this); //下载初始化
        initRetrofit();
        registToWX();
        CrashReport.initCrashReport(getApplicationContext(), "2eba41e64a", false);//bugly
      //  CrashReport.testJavaCrash();
        webviewSetPath();
        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
        initbox();
        initDbMaster();
        //红点清零
        badgeNumber = 0;
        Log.d("BadgeUtil", "myapplication红点显示个数" + MyApplication.badgeNumber);
        BadgeUtil.setBadgeCount(this, MyApplication.badgeNumber);

        initBackAndFront();
    }
    private void initBackAndFront() {

        MyLifecycleHandler helper = new MyLifecycleHandler();
        helper.register(this, new MyLifecycleHandler.OnAppStatusListener() {
            @Override
            public void onFront() {
                //应用切到前台处理
                Log.i("MyLifecycleHandler", "前台");
                badgeNumber = 0;
                Log.d("BadgeUtil", "myapplication红点显示个数" + MyApplication.badgeNumber);
                BadgeUtil.setBadgeCount(MyApplication.this, MyApplication.badgeNumber);

            }

            @Override
            public void onBack() {
                //应用切到后台处理
                Log.i("MyLifecycleHandler", "后台");


            }
        });
    }
    private void initDbMaster() {
        DaoMaster.DevOpenHelper test_userhelp = new DaoMaster.DevOpenHelper(this, "Jpush_db");
        SQLiteDatabase writableDatabase = test_userhelp.getWritableDatabase();
        daoMaster = new DaoMaster(writableDatabase);
        daoSession = daoMaster.newSession();
    }
    public static DaoSession getDbSession(){
        if(daoSession != null) {
            return daoSession;
        }
        return null;
    }

    public static DaoMaster getDaoMaster(){
        if(daoMaster != null){
            return daoMaster;
        }
        return null;
    }

    private void webviewSetPath() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(context);

            if (!getApplicationContext().getPackageName().equals(processName)) {//判断不等于默认进程名称
                WebView.setDataDirectorySuffix(processName);
            }
        }
    }


    public String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }
    private void initbox() {

        IBoxingMediaLoader loader = new BoxingGlideLoader();
        BoxingMediaLoader.getInstance().init(loader);

    }
    // 遍历所有Activity并finish
    public static void exit() {
        if (mActivities != null && mActivities.size() > 0) {

            for (Activity activity : mActivities) {
                activity.finish();
            }
        }

    }
    /**
     * 移除活动
     *
     * @param activity
     */
    public static void remove(Activity activity) {
        if (mActivities != null) {
            mActivities.remove(activity);
        }
    }
    /**
     * 初始化网络请求的
     */
    private void initRetrofit() {

        String token = SpUtils.getString(Contants.Token);
        //开启抓包谷歌浏览器抓包
//        if (BuildConfig.IS_DEBUG) {
//            opennetWorkDebug();
//        }
        opennetWorkDebug();

        String baseUrl;
        //获取当前是正式环境还是测试环境并且初始化网络

        if (BuildConfig.DEBUG) { //测试环境
            //判断是正式环境还是测试环境
            if (EnvironmentManager.isDebug(this)) {
                baseUrl = AppConfig.TEST_URL;
            } else {
                baseUrl = AppConfig.ONLINE_URL;
            }
            RetrofitFactory.getRetrofitFactory().init(this, baseUrl, token);
            NetServices.Factory.create();
            MCrashMonitor.init(this, true, new MCrashCallBack() {
                @Override
                public void onCrash(File file) {
                    //可以在这里保存标识，下次再次进入把日志发送给服务器
                    Log.i("myapplication", "CrashMonitor回调:" + file.getAbsolutePath());
                }
            });
        } else { //正式环境
            AppConfig.TEST = false;
            RetrofitFactory.getRetrofitFactory().init(this, AppConfig.ONLINE_URL, token);
            NetServices.Factory.create();
        }

    }

    private void opennetWorkDebug() {
        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
                        .build());
    }

    /**
     * 注册微信
     */
    private void registToWX() {
        mWxApi = WXPayEntryActivity.initWeiXin(this, Contants.WEIXIN_APP_ID);
    }

    public static Context getContext() {
        return context;
    }
}

